﻿using System;
using System.Linq;

namespace WenCong.WorkShop.Framework.Orm
{
    [AttributeUsage(AttributeTargets.Class)]
    public class DbFactoryAttribute : Attribute
    {
        public readonly string ConnectionName;

        public DbFactoryAttribute(string connectionName)
        {
            ConnectionName = connectionName;
        }

        public static string GetKeyFrom(object target)
        {
            const string defaultConnectionName = "DefaultDB";
            Type objectType = target.GetType();
            object[] attributes = objectType.GetCustomAttributes(typeof(DbFactoryAttribute), true);
            if (attributes.Length > 0)
            {
                var attribute = (DbFactoryAttribute)attributes[0];
                return attribute.ConnectionName;
            }

            string namespaces = objectType.Namespace;
            if (string.IsNullOrEmpty(namespaces))   return defaultConnectionName;
          //  if (namespaces.ToLower().EndsWith("data") || namespaces.ToLower().EndsWith("dao") || namespaces.ToLower().EndsWith("daos") || namespaces.ToLower().EndsWith("daoes"))
            if (namespaces.ToLower().EndsWith("dao"))   return defaultConnectionName;

            return namespaces.Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries).LastOrDefault();
        }
    }
}
